<template>
  <a-modal
    width="80%"
    v-model:visible="modelVisible"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <template #title>查看条码</template>
    <div id="QecodeContent">
      <div style="width: 100%; text-align: right; padding: 10px">
        <a-dropdown @select="handleSelect">
          <a-button type="primary">批量</a-button>
          <template #content>
            <a-doption @click="BatchDownload">条码下载</a-doption>
            <a-doption>条码打印</a-doption>
          </template>
        </a-dropdown>
      </div>
      <a-table
        :pagination="false"
        :data="qrCodeData"
        @page-change="pageChange($event, 'page')"
        @page-size-change="pageChange($event, 'size')"
        :row-selection="rowSelection"
        v-model:selectedKeys="selectedKeys"
        @select="onSelect"
        :args="args"
        row-key="id"
      >
        <template #columns>
          <a-table-column :width="80" align="center">
            <template #title> 序号 </template>
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column :width="100" title="条码" align="center"
            ><template #cell="{ record }">
              <QRcode
                ref="qrcode"
                :qr-url="`${record.content}`"
                :qr-text="`${record.content}`"
            /></template>
          </a-table-column>
          <a-table-column :width="100" title="条码格式" align="center"
            ><template #cell="{ record }">
              {{ record.format === 1 ? 'QR二维码' : '条形码' }}
            </template>
          </a-table-column>
          <a-table-column
            :width="100"
            title="条码类型"
            data-index="name"
            align="center"
            ><template #cell="{ record }">
              {{ record.type === 1 ? '物料条码' : '物料包装条码' }}
            </template>
          </a-table-column>
          <a-table-column
            :width="100"
            title="条码内容"
            data-index="location"
            align="center"
            ><template #cell="{ record }">
              <a-textarea
                v-model="record.content"
                placeholder="Please enter something"
                disabled
                allow-clear
              />
            </template>
          </a-table-column>
          <a-table-column
            :width="100"
            title="启用状态"
            data-index="tier"
            align="center"
            ><template #cell="{ record }">
              <a-typography-text type="success">
                {{ record.state === 1 ? '已启用' : '' }}
              </a-typography-text>
            </template>
          </a-table-column>
          <a-table-column
            :width="100"
            title="操作"
            data-index="tier"
            align="center"
            ><template #cell="{ record, rowIndex }">
              <a-space>
                <a-dropdown @select="handleSelect">
                  <a-button type="primary">更多功能</a-button>
                  <template #content>
                    <a-space direction="vertical" fill>
                      <a-button type="text">条码打印</a-button>
                      <a-button type="text" @click="bb(rowIndex)"
                        >条码下载</a-button
                      >
                      <a-popconfirm
                        content="确认删除?"
                        type="error"
                        @ok="delQrcode(record.id)"
                      >
                        <a-button type="text" status="danger"
                          >条码删除</a-button
                        >
                      </a-popconfirm>
                    </a-space>
                  </template>
                </a-dropdown>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, watchEffect } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { getBarcode, delarcode } from '@/api/barcode';
  import dayjs from 'dayjs';
  import { cloneDeep } from 'lodash';
  import Message from '@arco-design/web-vue/es/message';

  const qrcodeRef = ref();
  const router = useRouter();
  const route = useRoute();
  const props = withDefaults(
    defineProps<{
      visible: boolean;
      data: any;
    }>(),
    {}
  );

  const emit = defineEmits(['update:visible', 'selectProductEmit']);

  // 判断用户是否显示弹出框
  const modelVisible = computed({
    get() {
      return props.visible;
    },
    set(visible: boolean) {
      emit('update:visible', visible);
    },
  });

  const selectedKeys = ref([]);
  const selectedIndex = ref([]);

  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });

  const args = {
    bordered: {
      headerCell: true,
    },
    stripe: true,
  };

  const id = Number(route.query.id);
  // 获取对应列表信息
  const qrCodeData = ref();
  const getData = async () => {
    try {
      qrCodeData.value = props.data;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  getData();

  const onSelect = (e: any, id: number, d: any) => {
    const msg: any = qrCodeData.value.findIndex((i: any) => i.id === id);
    if (selectedIndex.value.indexOf(msg) === -1) {
      selectedIndex.value.push(msg);
    } else {
      const res = selectedIndex.value.splice(
        selectedIndex.value.indexOf(msg),
        1
      );
    }
  };

  const bb = (index: number) => {
    let canvas1 = document.getElementById('QecodeContent');
    if (!canvas1) return;
    let canvas = canvas1.getElementsByTagName('canvas');
    let a = document.createElement('a');
    a.href = canvas[index].toDataURL('img/png');
    a.download = '二维码';
    a.click();
  };

  const BatchDownload = () => {
    let canvas1 = document.getElementById('QecodeContent');
    if (!canvas1) return;
    let canvas = canvas1.getElementsByTagName('canvas');
    selectedIndex.value.forEach((item) => {
      let a = document.createElement('a');
      a.href = canvas[item].toDataURL('img/png');
      a.download = '二维码';
      a.click();
    });
  };

  const generateBarCode = () => {
    modelVisible.value = true;
  };

  const delQrcode = async (id?: number) => {
    await delarcode({ id });
    getData();
  };

  watchEffect(() => {
    if (modelVisible.value) {
      getData();
    }
  });
</script>

<style scoped lang="less">
  #content {
    padding: 20px;
  }

  .arco-space-item :nth-child(1) {
    text-align: right;
  }
</style>
